//
//  CamerVC.swift
//  day04
//
//  Created by 杨绍鑫 on 2018/9/7.
//  Copyright © 2018年 crcnet. All rights reserved.
//

import UIKit
import AVFoundation

class CamerVC: UIViewController {

    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var tmpView: UIImageView!
    
    var configsesion : AVCaptureSession?
    var stillImage : AVCaptureStillImageOutput?
    var prentCaptureLayer = AVCaptureVideoPreviewLayer()
    
    var isTakePhoto = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
         UIApplication.shared.isStatusBarHidden = true
        //bgView.layer.addSublayer(prentCaptureLayer)
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
       
        self.configsesion = AVCaptureSession()
        configsesion?.sessionPreset = .hd1920x1080

        let backCamera = AVCaptureDevice.default(for: AVMediaType.video)
        var error : NSError?
        var input: AVCaptureDeviceInput!
        
        do {
            input = try AVCaptureDeviceInput(device: backCamera!) }
        catch let error1 as NSError {
            error = error1
            input = nil
        }
        
        if (error == nil && configsesion?.canAddInput(input) != nil) {
            
            configsesion?.addInput(input)
            
            stillImage = AVCaptureStillImageOutput()
            stillImage?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]
            
            if (configsesion?.canAddOutput(stillImage!) != nil) {
                configsesion?.addOutput(stillImage!)
                
                prentCaptureLayer = AVCaptureVideoPreviewLayer(session: configsesion!)
                prentCaptureLayer.videoGravity = .resizeAspect
                prentCaptureLayer.connection?.videoOrientation = AVCaptureVideoOrientation.portrait
                self.bgView.layer.addSublayer(prentCaptureLayer)
                configsesion?.startRunning()
            }
            
        }

    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        prentCaptureLayer.frame = bgView.bounds
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.takePoton()
    }
    
    func takePoton() {
        
        if isTakePhoto == true {
            configsesion?.startRunning()
            self.didPressTakePhoto()
        } else {
           tmpView.isHidden = true
        }
         isTakePhoto = !isTakePhoto
    }
    
    func didPressTakePhoto()  {
        let connetion = stillImage?.connection(with: AVMediaType.video)
        if connetion != nil{
            connetion?.videoOrientation = .portrait
            stillImage?.captureStillImageAsynchronously(from: connetion!, completionHandler: { (buffer, erro) in
                if buffer != nil{
                    let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer!)
                    let dataProvider  = CGDataProvider(data: imageData as! CFData)
                    let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)
                    
                    let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.right)
                    
                    self.tmpView.image = image
                    self.tmpView.isHidden = false
                }
            })
        }
        
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
